//
//  JYJPersonViewController.m
//  导航测试demo
//
//  Created by JYJ on 2017/6/5.
//  Copyright © 2017年 baobeikeji. All rights reserved.
//

#import "JYJPersonViewController.h"
#import "JYJMyWalletViewController.h"
#import "JYJMyCardViewController.h"
#import "JYJMyTripViewController.h"
#import "JYJMyFriendViewController.h"
#import "JYJMyStickerViewController.h"
#import "JYJCommenItem.h"
#import "JYJProfileCell.h"
#import "JYJPushBaseViewController.h"
#import "JYJAnimateViewController.h"
#import "UserInfo.h"
#import "UserSites.h"
#import "MMZCViewController.h"
#import "JYJSliderMenuTool.h"
#import "WorkOrderModelCopy.h"
#import "WorkOrderModel.h"

@interface JYJPersonViewController () <UITableViewDelegate, UITableViewDataSource>
/** tableView */
@property (nonatomic, weak) UITableView *tableView;
/** headerIcon */
@property (nonatomic, weak) UIImageView *headerIcon;
/** data */
@property (nonatomic, strong) NSArray *data;
@property (nonatomic,strong) UIButton* role;
@property(nonatomic,strong)UserInfo* user;
@end

@implementation JYJPersonViewController

- (NSArray *)data {
    if (!_data) {
        self.data = [NSArray array];
    }
    return _data;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    [self postUI];
    [self setupData];
    [self.role setTitle:[UserInfo share].role.roleName forState:UIControlStateNormal];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tableView.frame = self.view.bounds;
    self.headerIcon.frame = CGRectMake(self.tableView.frame.size.width / 2 - 36, 69, 72, 72);
}
-(void)postUI{
    NSDictionary *params = @{
                             @"access_token" : [MySingleton sharedMySingleton].tokenID
                             };
//    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:@"digiops/app/user/getUsers" params:params success:^(id responseObj) {
        NSLog(@"");
        if (responseObj[@"result"]==[NSNull null]) {
            return;
        }
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //角色
        UserRole* role=[UserRole mj_objectWithKeyValues:responseObj[@"result"][@"role"]];
        [self.role setTitle:role.roleName forState:UIControlStateNormal];
        //用户
        UserInfo* user=[UserInfo mj_objectWithKeyValues:responseObj[@"result"]];
        self.user=user;
        //user share
        [UserInfo share].userNum=user.userNum;
        [UserInfo share].userName=user.userName;
        [UserInfo share].passWord=user.passWord;
        //不赋值role powertype问题
//        [UserInfo share].role=user.role;
        [UserInfo share].roleName=user.roleName;
        [UserInfo share].telephone=user.telephone;
        [UserInfo share].sites=user.sites;
        [UserInfo share].uuid=user.uuid;
//        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//        [user saveOrUpdate];//更改了bgfmdb版本

        //站点
//        for (NSDictionary* site in self.user.sites) {
//            UserSites* s=[UserSites mj_objectWithKeyValues:site];
//            NSLog(@"");
//        }
        if ([role.roleName isEqualToString:@"经理"]) {
            [self.headerIcon setImage:[UIImage imageNamed:@"avatar_manager"]];
        }
        else if([role.roleName isEqualToString:@"站点经理"])
        {
            [self.headerIcon setImage:[UIImage imageNamed:@"avatar_sitemanager"]];
        }
        NSLog(@"");
        //        rootViewController = nav;
    } failure:^(NSError *error) {
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

    }];
}
- (void)setupUI {
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    UIColor *color1=[UIColor colorWithHexString:@"#FE942C" alpha:1];
    UIColor *color2=[UIColor colorWithHexString:@"#FB573D" alpha:1];
    gradientLayer.colors = @[(__bridge id)color1.CGColor, (__bridge id)color2.CGColor];
    gradientLayer.locations = @[@0.5, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1.0, 0);
    CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
    if ([UIScreen mainScreen].bounds.size.width > 375) {
        width -= 50;
    } else if ([UIScreen mainScreen].bounds.size.width > 320) {
        width = width - 25;
    }
    gradientLayer.bounds = CGRectMake(0, 0, width*2, SCREEN_HEIGHT*2);
    [self.view.layer addSublayer:gradientLayer];
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.scrollEnabled = NO;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    UIView *headerView = [[UIView alloc] init];
//    headerView.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:247 / 255.0 blue:250 / 255.0 alpha:1.0];
    headerView.backgroundColor=[UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, 0, 200);
    self.tableView.tableHeaderView = headerView;
    
    /** 头像图片 */
    UIImageView *headerIcon = [[UIImageView alloc] init];
    headerIcon.image = [UIImage imageNamed:@"avatar_baoan"];
    headerIcon.frame = CGRectMake(0, 39, 72, 72);
    headerIcon.layer.cornerRadius = 36;
    headerIcon.clipsToBounds = YES;
    [headerView addSubview:headerIcon];
    self.headerIcon = headerIcon;
    self.headerIcon.userInteractionEnabled=YES;
    UITapGestureRecognizer * tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
    [self.headerIcon addGestureRecognizer:tapGesture1];
    
    //角色按钮
    UIButton* role=[[UIButton alloc] init];
//    role.frame=CGRectMake(5, 39+5, SCREEN_WIDTH/2-50, 30);
    [role setBackgroundColor:[UIColor clearColor]];
    [role.layer setBorderWidth:0.5];
    [role.layer setBorderColor:[UIColor whiteColor].CGColor];
    [role.layer setMasksToBounds:YES];
    [role.layer setCornerRadius:20.0];
    [role setTitle:@"" forState:UIControlStateNormal];
    role.titleLabel.textColor=[UIColor whiteColor];
    [role addTarget:self action:@selector(roleClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:role];
    self.role=role;
    
    [role mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(headerIcon).offset(0);
        make.bottom.mas_equalTo(headerView).offset(-5);
        make.height.mas_equalTo(@40);
        make.width.mas_equalTo(SCREEN_WIDTH/2-20);
    }];
    //    [self.layer setBorderWidth:1.0];   //边框宽度
    //    [self.layer setBorderColor:[UIColor colorWithRed:0.941 green:0.580 blue:0.408 alpha:1.000].CGColor];//边框颜色
    UIView* footView=[[UIView alloc] init];
//    footView.frame=CGRectMake(0,0,0,100);
    footView.backgroundColor=[UIColor clearColor];
    self.tableView.tableFooterView=footView;
    
    UIView* line=[[UIView alloc] init];
    line.backgroundColor=[UIColor whiteColor];
    [footView addSubview:line];
    
    [footView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(self.view).offset(0);
        make.height.mas_equalTo(@100);
        make.width.mas_equalTo(self.view);
    }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(footView).offset(0);
        make.height.mas_equalTo(@0.5);
        make.width.mas_equalTo(footView);
    }];
    
    UIButton* logo=[[UIButton alloc] init];
    //    role.frame=CGRectMake(5, 39+5, SCREEN_WIDTH/2-50, 30);
    [logo setBackgroundColor:[UIColor clearColor]];
    [logo setTitle:@"ADEN DIGIOPS V1.4" forState:UIControlStateNormal];
    logo.titleLabel.font=[UIFont systemFontOfSize:12.0];
    logo.titleLabel.textColor=[UIColor whiteColor];
    [headerView addSubview:logo];
    [logo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(footView);
        make.width.mas_equalTo(@130);
        make.height.mas_equalTo(@30);
        make.bottom.mas_equalTo(line).offset(-20);
    }];
    
    UIImageView *logoIcon = [[UIImageView alloc] init];
    logoIcon.image = [UIImage imageNamed:@"ic_header_logo"];
    [headerView addSubview:logoIcon];
    [logoIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(logo);
        make.size.mas_equalTo(@15);
        make.right.mas_equalTo(logo.mas_left).offset(0);
    }];
    
    UIButton* logout=[[UIButton alloc] init];
    //    role.frame=CGRectMake(5, 39+5, SCREEN_WIDTH/2-50, 30);
    [logout setBackgroundColor:[UIColor clearColor]];
    [logout setTitle:@"退出" forState:UIControlStateNormal];
    logout.titleLabel.textColor=[UIColor whiteColor];
    [logout addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:logout];
    [logout mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(footView);
        make.width.mas_equalTo(@60);
        make.height.mas_equalTo(@40);
        make.bottom.mas_equalTo(self.view).offset(-30);
    }];
    footView.userInteractionEnabled=YES;
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(logout)];
    [footView addGestureRecognizer:tapGesture];
}
-(void)logout{
    [self postLogoutUI];
}
-(void)tapGestureRecognizer{
    [self roleClick];
}
-(void)roleClick{
    JYJPushBaseViewController *vc = [[JYJMyWalletViewController alloc] init];
    vc.title = @"个人信息";
    vc.user=self.user;
    vc.animateViewController = (JYJAnimateViewController *)self.parentViewController;
    [self.parentViewController.navigationController pushViewController:vc animated:YES];
}
- (void)setupData {
    JYJCommenItem *myWallet = [JYJCommenItem itemWithIcon:nil title:@"" subtitle:@"" destVcClass:[JYJMyWalletViewController class]];
    
    JYJCommenItem *myCoupon = [JYJCommenItem itemWithIcon:nil title:@"联系方式" subtitle:@"" destVcClass:[JYJMyCardViewController class]];
//
    JYJCommenItem *myTrip = [JYJCommenItem itemWithIcon:@"nil" title:@"热线电话" subtitle:nil destVcClass:[JYJMyTripViewController class]];
//
//    JYJCommenItem *myFriend = [JYJCommenItem itemWithIcon:@"menu_invite" title:@"邀请好友" subtitle:nil destVcClass:[JYJMyFriendViewController class]];
//
//    JYJCommenItem *mySticker = [JYJCommenItem itemWithIcon:@"menu_sticker" title:@"我的贴纸" subtitle:nil destVcClass:[JYJMyStickerViewController class]];
    self.data = @[myWallet, myCoupon,myTrip];
}

#pragma mark - TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建cell
    JYJProfileCell *cell = [JYJProfileCell cellWithTableView:tableView];
    cell.backgroundColor=[UIColor clearColor];
    cell.item = self.data[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 74;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    JYJCommenItem *item = self.data[indexPath.row];
    if (item.destVcClass == nil) return;
    
    JYJPushBaseViewController *vc = [[item.destVcClass alloc] init];
    vc.title = item.title;
    vc.animateViewController = (JYJAnimateViewController *)self.parentViewController;
    [self.parentViewController.navigationController pushViewController:vc animated:YES];
}

-(void)postLogoutUI{
    NSDictionary *params = @{
                             @"access_token" : [MySingleton sharedMySingleton].tokenID
                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:@"auth/oauth/removeToken" params:params success:^(id responseObj) {
        NSLog(@"");
//        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//        [defaults removeObjectForKey:@"updatetime"];
//        [defaults synchronize];
//        //清工单数据
//        [WorkOrderModel clear];
//        [WorkOrderModelCopy clear];
        
        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"注销成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
        [JYJSliderMenuTool hide];
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

        //        rootViewController = nav;
        MMZCViewController * homeVC = [[MMZCViewController alloc]init];
        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
        // 添加为子控制器
        nav.title = @"任务箱";
        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
        //清除token
        //本地存token
        NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
        [defaults2 removeObjectForKey:@"accessToken"];
        [defaults2 removeObjectForKey:@"refreshToken"];
        [defaults2 synchronize];
        
    } failure:^(NSError *error) {
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
